//============================================用户登录判断及基本功能参数================================================
if(!$.cookie("MYID")){
    var returnurl=encodeURIComponent("http://www.pulu.com/weixin/chatpage.html"); //同意后跳转页面
    if(is_weixn()){
        //先微信验证获取openid 如果已经授权过了 直接页面截取openid 然后发送请求获取 用户的ID
        var reg=new RegExp("code=[a-zA-Z0-9]*");
        if(window.location.href.match(reg)&&$.cookie("wx")=="over"){
            var code=window.location.href.match(reg);
            $.ajax({
                type:"GET",
                url:"GetOpenId.ashx?"+code,
                async: false,
                success:function(data){
                    var dat=data;
                    $.cookie("wxod",dat);
                    $.cookie("wxopenid",dat);
                    //发请求获取用户的id
                    $.ajax({
                        type:"GET",
                        url:getwxopenidurl+dat,
                        success:function(d){
                            //如果没有用户id 则证明用户是第一次登陆 保存openid跳转至登录页面
                            if(!d.Data||!d.Data.userId){
                                //微信跳转进来的
                                if(!$.cookie("MYID")||$.cookie("MYID").length<10){
                                    $.cookie("wxopenid",dat);
                                    location.href="http://www.pulu.com/weixin/login.html"
                                }
                                //退出登录的
                            }else if(d.Data&&d.Data.userId.length>0){
                                $.cookie("wxopenid",d.Data.openId);
                                $.cookie("MYID",d.Data.userId);
                                $.cookie("MYAVA",d.Data.userAva);
                                $.cookie("MYNICK",d.Data.userNick);
                                location.href="http://www.pulu.com/weixin/chatpage.html";
                            }
                        }
                    })
                }
            })
        }
        else{
            $.cookie("wx","over");
            location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx658c34793ecfd9f9&redirect_uri="+returnurl+"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
        }
    }
    else{
        location.href="http://www.pulu.com/weixin/login.html";
    }
}
var newsbtn=document.getElementById("news");//消息按钮
var listplace=document.getElementById("listplace");//好友列表
var rightnav=document.getElementsByClassName("rightnav")[0];//信息提示页
var friendsbtn=document.getElementById("friends");//好友按钮
var newsplace=document.getElementById("newsplace");//信息提示页
//页面切换
newsbtn.onclick=function(){
    $(window).scrollTop(0);
    friendsbtn.className="";
    newsbtn.className="isclick";
    newsplace.style.display="block";
    listplace.style.display="none";
    rightnav.style.display="none";
    $.cookie("liuyan","read");//留言已经看过
    $.cookie("friendotherpage","");
};
friendsbtn.onclick=function(){
    $(window).scrollTop(0);
    friendsbtn.className="isclick";
    newsbtn.className="";
    listplace.style.display="block";
    rightnav.style.display="block";
    newsplace.style.display="none";
    $.cookie("friendotherpage","yes");
};
var fromurl=document.referrer;

document.getElementsByClassName("mweb_modal_back_button")[0].onclick=function(){
    if(fromurl&&!/chatpage.html/.test(fromurl)){
        history.go(-1);
    }
    else{
        location.href="pulu.html";
    }
};
document.getElementById("newfriendbtn").onclick=function(){
    location.href="addnewfriends.html";
};
//可能认识的人
document.getElementById("strangepeople").onclick=function(){
    location.href="relapeoplelist.html?showallrela";
};
//历史消息
document.getElementById("historynote").onclick=function(){
    location.href="mynotichistory.html?fromchatpage=1";
};
//标签
document.getElementById("biaoqian").onclick=function(){
    location.href="addlabel.html";
};
//-----------------------------------------------------
//时间 几天前 几分钟前
function getDateTimeStamp(dateStr){
    dateStr=dateStr.match(/[0-9\-T\:]+/)[0].replace(/T/g,' ');
    return Date.parse(dateStr.replace(/-/gi,"/"));
}
function getDateDiff(dateTimeStamp){
    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var halfamonth = day * 15;
    var month = day * 30;
    var now = new Date().getTime();
    var diffValue = now - dateTimeStamp;
    if(diffValue < 0){ result="刚刚";return;}
    var monthC =diffValue/month;
    var weekC =diffValue/(7*day);
    var dayC =diffValue/day;
    var hourC =diffValue/hour;
    var minC =diffValue/minute;
    if(monthC>=1){result="" + parseInt(monthC) + "月前";}
    else if(weekC>=1){result="" + parseInt(weekC) + "周前";}
    else if(dayC>=1){result=""+ parseInt(dayC) +"天前";}
    else if(hourC>=1){result=""+ parseInt(hourC) +"小时前";}
    else if(minC>=1){result=""+ parseInt(minC) +"分钟前";}
    else result="刚刚";
    return result;
}
//-----------------------------------------------------
var hasharr={};//判断字母是否存在
if($.cookie("MYID")){id=$.cookie("MYID")};

function gotochat(e){
    location.href="chatingonepeople.html?otherid="+ e.dataset.uid;
}
//展示加载图片
function showloadimg(e){
    $(e).fadeIn();
};
//============================================================红点======================================================
if($.cookie("comefrom")=="addnewfriends"||$.cookie("friendotherpage")=="yes"||$.cookie("friendMsgNum")||$.cookie("changeFMN")=="changed"){
    //$.cookie("comefrom","");//来自新的好友页面 页面返回
    $.cookie("friendotherpage","");//好友详情页返回定位锚
    friendsbtn.className="isclick";
    newsbtn.className="";
    listplace.style.display="block";
    rightnav.style.display="block";
    newsplace.style.display="none";
}
else{
    ////申请通知
    //$.ajax({
    //    type:"get",
    //    url:getfriendnotenumurl+id,
    //    datatype:"json",
    //    success:function(d){
    //        if(d.Data>0){
    //            $.cookie("indexFriendNum",d.Data);//首页获取的好友申请个数
    //            $("#newfriendbtn i").css("display","block");
    //            //好友页面红点
    //            if(/chatpage/.test(location.href)){
    //                $("#chatpageheader>i").css("display","block");
    //            }
    //        }else{
    //            $.cookie("indexFriendNum","0");
    //        }
    //    }
    //});
}
//============================================================加载======================================================
if($.cookie("delFriend")=="true"){$.cookie("delFriend","");location.reload();}//他人也删除好友返回
$().ready(function(){
    //来自主页 消息通知模板
    if(/pulu.html/.test(document.referrer)||/mynotic/.test(document.referrer)||/chatpage.html/.test(document.referrer)||!document.referrer){
        console.log("清除："+document.referrer);
        //$.cookie("comefrom","");//来自新的好友页面 页面返回
        $.cookie("friendotherpage","");//好友详情页返回定位锚
        friendsbtn.className="isclick";
        newsbtn.className="";
        listplace.style.display="block";
        rightnav.style.display="block";
        newsplace.style.display="none";
    };

    if(/fellower.html/.test(document.referrer)){
        friendsbtn.className="";
        newsbtn.className="isclick";
        listplace.style.display="none";
        rightnav.style.display="none";
        newsplace.style.display="block";
    }

    //展示页面
    if($.cookie("chatpageNote")=="note"&&!/showFriend/.test(location.href)){
        $.cookie("chatpageNote","");
        friendsbtn.className="";
        newsbtn.className="isclick";
        listplace.style.display="none";
        rightnav.style.display="none";
        newsplace.style.display="block";
    }
    //获得关注人列表
    $.ajax({
        datatype:"json",
        type:"get",
        url:getPuluTopLayer+"?userId="+id,
        success:function(d){
            console.log(d);
            if(d.Data&&d.Data.length>0){
                //排序
                //var friendarr= d.Data;
                //console.log(d.Data);
                var friendarr= (d.Data).sort(compare);
                //console.log(friendarr);
                hasharr={};//判断字母是否存在
                for(var i=0;i<friendarr.length;i++){
                    if(friendarr[i].userName){
                        friendarr[this.index]=i;
                        //如果昵称开头为汉字或英文字母
                        var key=Pinyin.getCamelChars(friendarr[i].userName[0]);
                        var headimg="<img src='img/af8.png' class='topic_photo_img'/> ";
                        if(friendarr[i].headImg){
                            headimg="<img src='http://42.62.66.198:8003/"+friendarr[i].headImg+"' class='topic_photo_img' onload='showloadimg(this)' style='display:none;'/> ";
                        }
                        if(key.match(/[a-z|A-Z]/)){
                            key=key.toLowerCase();
                            if(!hasharr[Pinyin.getCamelChars(friendarr[i].userName[0])]){
                                hasharr[Pinyin.getCamelChars(friendarr[i].userName[0])]=i;
                            }
                            var realname="";
                            if(friendarr[i].realName){realname=" ("+friendarr[i].realName+")";}
                            $("#a").append("<div class='section_header section_header_gray zimutitle"+key+"' data-num='"+i+"' style='display:none'> <span class='"+key+"'>"+key+"</span> </div><div class='friends'> <div class='imageplace'><a href='otherpeoplepage.html?otherid="+friendarr[i].userId+"'>"+headimg+"</a> </div> <div class='innerplace'> <a href='chatingonepeople.html?otherid="+friendarr[i].userId+"'><span class='tc_text'>"+friendarr[i].userName+realname+"</span> </a> </div> </div>");
                        }else{
                            $("#jinghao").css("display","block");
                            var realname="";
                            if(friendarr[i].realName){realname=" ("+friendarr[i].realName+")";}
                            $("#jinghao").append("<div class='friends'> <div class='imageplace'><a href='otherpeoplepage.html?otherid="+friendarr[i].userId+"'>"+headimg+"</a> </div> <div class='innerplace'> <a href='chatingonepeople.html?otherid="+friendarr[i].userId+"'> <span class='tc_text'>"+friendarr[i].userName+realname+"</span> </a> </div> </div>");
                        };
                    }
                }
                //console.log(hasharr);
                for(var key in hasharr){
                    var classname="'.zimutitle"+key+"'";
                    key=key.toLowerCase();
                    $("div.zimutitle"+key).eq(0).css("display","block");
                    $("div.zimutitle"+key).eq(0).attr('id',key);
                };
            }
        }
    });

    //获取所有留言
    $.ajax({
        datatype:"json",
        type:"get",
        //url:"https://www.pulu.com/webapi/api/pulutalk/GetAllTalkMsgByUserId?userId="+id,
        url:"https://www.pulu.com/webapi/api/pulutalk/GetMsgByUserId?userId="+id,
        success:function(d){
            if(d.Data&& d.Data.length>0){
                for(var i=0;i< d.Data.length;i++){
                    var uid=d.Data[i].list[0].friendId;//跳转id
                    var avaimg="<img src='img/af8.png' class='topic_photo_img'>";
                    if(d.Data[i].list[0].friendHeadImg){
                        avaimg="<img src='"+imgurl+d.Data[i].list[0].friendHeadImg+"' class='topic_photo_img' onload='showloadimg(this)' style='display:none;'>";
                    }
                    var msg="";
                    if(d.Data[i].list[0].msg){
                        msg=codetoface(d.Data[i].list[0].msg);
                    }
                    var fid=d.Data[i].list[0].friendId,
                        fnick=d.Data[i].list[0].friendNick;
                    if(d.Data[i].list[0].friendId==id){ //陌生人留言 返回相反
                        uid=d.Data[i].list[0].userId;//跳转id
                        fid=d.Data[i].list[0].userId;
                        if(d.Data[i].list[0].userHeadImg){
                            avaimg="<img src='"+imgurl+d.Data[i].list[0].userHeadImg+"' class='topic_photo_img' onload='showloadimg(this)' style='display:none;'>";
                        }else{
                            avaimg="<img src='img/af8.png' class='topic_photo_img'>";
                        }
                        fnick=d.Data[i].list[0].userNick;
                    }

                    var tim="";
                    if(d.Data[i].list[0].ctime){
                        tim=getDateDiff(getDateTimeStamp(d.Data[i].list[0].ctime));
                    }
                    if(!tim){
                        tim="刚刚";
                    }
                    var showtime="<span class='showtime rt'>"+tim+"</span>";

                    $("#newsplace").append("<div class='friends'><div class='imageplace'><a href='otherpeoplepage.html?otherid="+uid+"'>"+avaimg+"</a></div><div class='innerplace wordplace' onclick='gotochat(this)' data-uid="+fid+">"+showtime+"<span class='tc_text'>"+fnick+"</span><p>"+msg+"</p></div></div>");
                }
            }else{
                $("#newsplace").append("<p>没有更多消息</p>")
            }
        }
    });

    //留言通知
    $.ajax({
        type:"get",
        url:messagenotenumurl+id,
        datatype:"json",
        success:function(d){
            //console.log(d);
            if(d.Data.msg=="有新留言"){
                $("#news i").css("display","block");
            }
        }
    });
    //右侧导航条点击跳转
    //字母键
    var englishbtn=document.querySelectorAll(".rightnav div.zmbtn");//导航条跳转
    var tonum=0;
    for(var en=0;en<englishbtn.length;en++){
        englishbtn[en].onclick=function(e){
            //console.log("点击的是："+e.target.innerHTML);
            var key=e.target.innerHTML.toLowerCase();
            if($("#"+key).offset().top){
                var englishOffsetTop=$("#"+key).offset().top;
                var scrollTop=$("#"+key).offset().top-44;
                $(window).scrollTop(scrollTop);
            }
        };
    };
});
//===================================================微信扫一扫=========================================================
//if(is_weixn()){
//    $("#scan").css("display","block");
//    $.ajax({
//        type:"GET",
//        url:"GetSign.ashx?p=weixin/chatpage.html",
//        success:function(data){
//            timestampone=data.timestamp;
//            nonceStrone=data.nonceStr;
//            signatureone=data.signature;
//            wx.config({
//                debug: false,
//                appId: 'wx658c34793ecfd9f9',
//                timestamp:timestampone, //时间戳
//                nonceStr:nonceStrone,  //随机字符串
//                signature:signatureone,  //SHA1编码
//                jsApiList: [
//                    // 所有要调用的 API 都要加到这个列表中
//                    "scanQRCode"
//                ]
//            });
//        }
//    });
//}
//
//$("#scan").click(function(){
//    wx.scanQRCode({
//        needResult: 0, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
//        scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码，默认二者都有
//        success: function (res) {
//            var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
//        }
//    });
//});